import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../common/widgets/cached_image.dart';
import '../../../common/utils/toast_util.dart';
import 'index.dart';

/// 活动发布页面
/// 
/// 🎨 UI设计风格：现代化卡片式设计 + 白色主题 + 渐变点缀
/// 
/// 设计特点：
/// - 采用白色卡片布局，清晰的层次结构
/// - 使用红色渐变作为品牌色，突出重点
/// - 统一的圆角（12px）、间距（10px）、阴影系统
/// - 渐变图标背景、彩色按钮阴影等精致细节
/// 
/// 功能特点：
/// - 使用企业级 Form 模型管理表单状态
/// - 集成高德地图位置选择
/// - 智能时间选择（最短30分钟，最长7天）
/// - 实时图片上传和预览
class ActivitePubilshPage extends GetView<ActivitePubilshController> {
  const ActivitePubilshPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA), // 🎨 设计规范：背景色
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: const Text(
          '发布活动',
          style: TextStyle(
            color: Color(0xFF333333), // 🎨 设计规范：文字主色
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        iconTheme: const IconThemeData(color: Color(0xFF333333)),
      ),
      body: SafeArea(
        child: _buildView(),
      ),
    );
  }

  // 主视图
  Widget _buildView() {
    return GestureDetector(
      // 点击页面其他地方时收起键盘
      onTap: () => controller.clearAllFocus(),
      child: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), // 🎨 设计规范：页面边距
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 📝 基础信息卡片
            _buildBasicInfoCard(),
            
            const SizedBox(height: 6), // 🎨 设计规范：卡片间距
            
            // 📍 地点信息卡片
            _buildLocationCard(),
            
            const SizedBox(height: 6),
            
            // ⏰ 时间信息卡片
            _buildTimeInfoCard(),
            
            const SizedBox(height: 6),
            
            // 🎯 活动设置卡片
            _buildActivitySettingsCard(),
            
            const SizedBox(height: 6),
            
            // 📄 活动详情卡片
            _buildEventDetailsCard(),
            
            const SizedBox(height: 6),
            
            // 🖼️ 活动封面卡片
            _buildImageUploadCard(),
            
            const SizedBox(height: 16),
            
            // 发布按钮
            _buildPublishButton(),
            
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
  
  // ==================== 🎨 卡片组件（符合设计规范）====================
  
  /// 📝 基础信息卡片
  Widget _buildBasicInfoCard() {
    return _buildCard(
      title: '基础信息',
      icon: Icons.edit_note_rounded,
      child: Column(
        children: [
          // 标题输入
          _buildInputRow(
            label: '标题',
            placeholder: '请输入活动标题',
            controller: controller.titleController,
            focusNode: controller.titleFocusNode,
          ),
        ],
      ),
    );
  }
  
  /// 📍 地点信息卡片
  Widget _buildLocationCard() {
    return _buildCard(
      title: '活动地点',
      icon: Icons.location_on_rounded,
      child: Column(
        children: [
          GestureDetector(
            onTap: () async {
              await controller.openMapForLocation();
            },
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFF8F9FA),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  // 定位图标
                  Obx(() => controller.isLocationLoading.value
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B6B)),
                          ),
                        )
                      : Container(
                          padding: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                            ),
                            borderRadius: BorderRadius.circular(6),
                          ),
                          child: const Icon(
                            Icons.location_on,
                            color: Colors.white,
                            size: 14,
                          ),
                        ),
                  ),
                  const SizedBox(width: 8),
                  // 位置文本
                  Expanded(
                    child: Obx(() => Text(
                      controller.form.value.location,
                      style: TextStyle(
                        fontSize: 13,
                        color: controller.isLocationLoading.value
                            ? const Color(0xFF999999)
                            : (controller.form.value.isDefaultLocation
                                ? const Color(0xFF999999)
                                : const Color(0xFF333333)),
                        fontWeight: FontWeight.w500,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                    )),
                  ),
                  // 刷新按钮
                  Obx(() => GestureDetector(
                    onTap: controller.isLocationLoading.value ? null : controller.refreshLocation,
                    child: Container(
                      padding: const EdgeInsets.all(6),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Icon(
                        Icons.refresh,
                        size: 16,
                        color: controller.isLocationLoading.value 
                            ? const Color(0xFF999999)
                            : const Color(0xFFFF6B6B),
                      ),
                    ),
                  )),
                  const SizedBox(width: 6),
                  // 跳转箭头
                  Icon(
                    Icons.chevron_right,
                    color: Colors.grey[400],
                    size: 20,
                  ),
                ],
              ),
            ),
          ),
          // 位置状态提示
          Obx(() => controller.form.value.isDefaultLocation
              ? Container(
                  margin: const EdgeInsets.only(top: 8),
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF8E1),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.info_outline, size: 14, color: Color(0xFFFF9800)),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(
                          '正在使用默认位置，点击选择位置',
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.orange[900],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              : const SizedBox.shrink()),
        ],
      ),
    );
  }
  
  /// ⏰ 时间信息卡片
  Widget _buildTimeInfoCard() {
    return _buildCard(
      title: '活动时间',
      icon: Icons.access_time_rounded,
      child: Column(
        children: [
          // 开始时间
          Obx(() => _buildSelectRow(
            label: '开始时间',
            value: controller.form.value.startDateText,
            placeholder: '请选择开始时间',
            onTap: () => controller.openDateTimePicker(Get.context!, true),
          )),
          const SizedBox(height: 10),
          // 结束时间
          Obx(() => _buildSelectRow(
            label: '结束时间',
            value: controller.form.value.endDateText,
            placeholder: '请选择结束时间',
            onTap: () {
              if (controller.form.value.startDate == null) {
                ToastUtil.warning('请先选择开始时间');
                return;
              }
              controller.openDateTimePicker(Get.context!, false);
            },
          )),
          // 时间规则提示
          Container(
            margin: const EdgeInsets.only(top: 10),
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: const Color(0xFFFFF8E1),
              borderRadius: BorderRadius.circular(6),
              border: const Border(
                left: BorderSide(color: Color(0xFFFFC107), width: 3),
              ),
            ),
            child: Row(
              children: [
                const Text('⏱️', style: TextStyle(fontSize: 14)),
                const SizedBox(width: 6),
                Expanded(
                  child: Text(
                    '活动时长：最短30分钟，最长7天',
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.orange[900],
                      height: 1.3,
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 持续时间显示
          Obx(() {
            if (controller.form.value.startDate != null && 
                controller.form.value.endDate != null) {
              return Container(
                margin: const EdgeInsets.only(top: 10),
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: const Color(0xFFF8F9FA),
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(color: const Color(0xFFE0E0E0)),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: const [
                        Icon(Icons.schedule, size: 14, color: Color(0xFF666666)),
                        SizedBox(width: 4),
                        Text(
                          '活动时间',
                          style: TextStyle(
                            fontSize: 12,
                            color: Color(0xFF666666),
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '${controller.form.value.startDateText} 至 ${controller.form.value.endDateText}',
                      style: const TextStyle(
                        fontSize: 11,
                        color: Color(0xFF333333),
                        height: 1.4,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFF66BB6A), Color(0xFF4CAF50)],
                        ),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        '持续: ${controller.form.value.durationDisplayText}',
                        style: const TextStyle(
                          fontSize: 10,
                          color: Colors.white,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              );
            }
            return const SizedBox.shrink();
          }),
        ],
      ),
    );
  }
  
  /// 🎯 活动设置卡片
  Widget _buildActivitySettingsCard() {
    return _buildCard(
      title: '活动设置',
      icon: Icons.settings_rounded,
      child: Column(
        children: [
          // 限制
          Obx(() => _buildSelectRow(
            label: '限制',
            value: controller.form.value.selectedLimit,
            placeholder: '请选择限制',
            onTap: () => controller.openLimitPicker(Get.context!),
          )),
          const SizedBox(height: 10),
          // 人数
          _buildInputRow(
            label: '人数',
            placeholder: '请输入参与人数',
            controller: controller.peopleCountController,
            focusNode: controller.peopleCountFocusNode,
            isNumberInput: true,
          ),
          const SizedBox(height: 10),
          // 消费
          Obx(() => _buildSelectRow(
            label: '消费',
            value: controller.form.value.selectedPayment,
            placeholder: '请选择消费方式',
            onTap: () => controller.openPaymentPicker(Get.context!),
          )),
        ],
      ),
    );
  }
  
  /// 📄 活动详情卡片
  Widget _buildEventDetailsCard() {
    return _buildCard(
      title: '活动详情',
      icon: Icons.description_rounded,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            decoration: BoxDecoration(
              color: const Color(0xFFF8F9FA),
              borderRadius: BorderRadius.circular(8),
            ),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            child: TextField(
              controller: controller.detailsController,
              focusNode: controller.detailsFocusNode,
              maxLines: 5,
              maxLength: 150,
              textInputAction: TextInputAction.done,
              onSubmitted: (value) {
                controller.detailsFocusNode.unfocus();
              },
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF333333),
              ),
              decoration: InputDecoration(
                hintText: '请输入活动详情说明...',
                hintStyle: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 13,
                ),
                border: InputBorder.none,
                counterText: '',
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ),
          const SizedBox(height: 6),
          Align(
            alignment: Alignment.centerRight,
            child: Obx(() => Text(
              '${controller.form.value.details.length}/150',
              style: const TextStyle(
                fontSize: 11,
                color: Color(0xFF999999),
              ),
            )),
          ),
        ],
      ),
    );
  }
  
  /// 🖼️ 活动封面卡片
  Widget _buildImageUploadCard() {
    return _buildCard(
      title: '活动封面',
      icon: Icons.image_rounded,
      trailing: Obx(() => Text(
        controller.form.value.imageCountText,
        style: TextStyle(
          fontSize: 12,
          color: controller.form.value.isImageLimitReached 
              ? const Color(0xFFFF6B6B) 
              : const Color(0xFF999999),
          fontWeight: FontWeight.w500,
        ),
      )),
      child: _buildImageUploadSection(),
    );
  }
  
  // ==================== 🧩 辅助组件 ====================
  
  /// 卡片容器（符合设计规范）
  Widget _buildCard({
    required String title,
    required IconData icon,
    required Widget child,
    Widget? trailing,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 0, vertical: 0), // 🎨 卡片外边距
      padding: const EdgeInsets.all(12.0), // 🎨 卡片内边距
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12), // 🎨 圆角
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04), // 🎨 Level 1 阴影
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题栏
          Row(
            children: [
              // 🎨 中性图标背景（浅灰色）
              Container(
                padding: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                  color: const Color(0xFFF5F5F5),  // 浅灰色背景
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  icon,
                  color: const Color(0xFF666666),  // 深灰色图标
                  size: 14,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                title,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
              if (trailing != null) ...[
                const Spacer(),
                trailing,
              ],
            ],
          ),
          const SizedBox(height: 12),
          // 内容
          child,
        ],
      ),
    );
  }
  
  /// 输入行组件
  Widget _buildInputRow({
    required String label,
    required String placeholder,
    required TextEditingController controller,
    required FocusNode focusNode,
    bool isNumberInput = false,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: BoxDecoration(
        color: const Color(0xFFF8F9FA),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 13,
              color: Color(0xFF666666),
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: TextField(
              controller: controller,
              focusNode: focusNode,
              textAlign: TextAlign.right,
              textInputAction: TextInputAction.done,
              keyboardType: isNumberInput ? TextInputType.number : TextInputType.text,
              inputFormatters: isNumberInput ? [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(3),
              ] : null,
              onSubmitted: (value) {
                focusNode.unfocus();
              },
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF333333),
                fontWeight: FontWeight.w500,
              ),
              decoration: InputDecoration(
                hintText: placeholder,
                hintStyle: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 13,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
                isDense: true,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 选择行组件
  Widget _buildSelectRow({
    required String label,
    required String value,
    required String placeholder,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        decoration: BoxDecoration(
          color: const Color(0xFFF8F9FA),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Text(
              label,
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF666666),
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                value.isEmpty ? placeholder : value,
                textAlign: TextAlign.right,
                style: TextStyle(
                  fontSize: 13,
                  color: value.isEmpty ? Colors.grey[400] : const Color(0xFF333333),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            const SizedBox(width: 8),
            Icon(
              Icons.chevron_right,
              color: Colors.grey[400],
              size: 18,
            ),
          ],
        ),
      ),
    );
  }
  
  /// 图片上传区域
  Widget _buildImageUploadSection() {
    return Obx(() {
      final imageList = controller.form.value.activityImages;
      final isUploading = controller.isUploadingImage.value;
      
      return Wrap(
        spacing: 8,
        runSpacing: 8,
        children: [
          // 显示已选择的图片
          ...imageList.asMap().entries.map((entry) {
            final index = entry.key;
            final imagePath = entry.value;
            
            return Stack(
              children: [
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      color: const Color(0xFFE0E0E0),
                      width: 1.5,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.04),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: imagePath.startsWith('http')
                        ? CachedImage(
                            imageUrl: imagePath,
                            width: 80,
                            height: 80,
                            fit: BoxFit.cover,
                            borderRadius: 8,
                          )
                        : Image.file(
                            File(imagePath),
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                color: const Color(0xFFF8F9FA),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(Icons.image_not_supported, size: 20, color: Colors.grey[400]),
                                    const SizedBox(height: 2),
                                    Text(
                                      '图片错误',
                                      style: TextStyle(fontSize: 8, color: Colors.grey[500]),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                  ),
                ),
                // 删除按钮
                Positioned(
                  top: -2,
                  right: -2,
                  child: GestureDetector(
                    onTap: () {
                      controller.clearAllFocus();
                      controller.removeActivityImage(index);
                    },
                    child: Container(
                      width: 22,
                      height: 22,
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                        ),
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFFD84545).withOpacity(0.3),
                            blurRadius: 4,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: const Icon(
                        Icons.close,
                        size: 14,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            );
          }),
          
          // 添加图片按钮
          if (!controller.form.value.isImageLimitReached)
            GestureDetector(
              onTap: () => controller.pickActivityImage(),
              child: Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  color: const Color(0xFFF8F9FA),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: const Color(0xFFE0E0E0),
                    width: 1.5,
                  ),
                ),
                child: isUploading
                    ? Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B6B)),
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '上传中...',
                            style: TextStyle(
                              fontSize: 9,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            padding: const EdgeInsets.all(6),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                              ),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            child: const Icon(
                              Icons.add_photo_alternate_rounded,
                              size: 20,
                              color: Colors.white,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            imageList.isEmpty ? '添加图片' : '继续添加',
                            style: TextStyle(
                              fontSize: 9,
                              color: Colors.grey[600],
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
              ),
            ),
        ],
      );
    });
  }
  
  /// 发布按钮（符合设计规范）
  Widget _buildPublishButton() {
    return Obx(() {
      final isLoading = controller.isLoading.value;
      
      return Container(
        height: 50,
        decoration: BoxDecoration(
          gradient: isLoading 
              ? null 
              : const LinearGradient(
                  colors: [Color(0xFFFF6B6B), Color(0xFFD84545)], // 🎨 主色渐变
                ),
          color: isLoading ? Colors.grey[400] : null,
          borderRadius: BorderRadius.circular(12), // 🎨 圆角
          boxShadow: isLoading 
              ? null 
              : [
                  BoxShadow(
                    color: const Color(0xFFD84545).withOpacity(0.3), // 🎨 彩色阴影
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
        ),
        child: ElevatedButton(
          onPressed: isLoading ? null : controller.submitForm,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.transparent,
            foregroundColor: Colors.white,
            shadowColor: Colors.transparent,
            elevation: 0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          child: isLoading
              ? Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.5,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                    SizedBox(width: 10),
                    Text(
                      '发布中...',
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ],
                )
              : Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    Icon(Icons.rocket_launch_rounded, size: 20),
                    SizedBox(width: 8),
                    Text(
                      '立即发布',
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
        ),
      );
    });
  }
}
